#include "pubmedgffreader.h"

PubMedGffReader::PubMedGffReader(QString gffFileName, QHash<QString, QString> clusterHashTable, QObject *parent) :
    clusterHashTable(clusterHashTable), GffReader(gffFileName, parent)
{
    qDebug() << "PubMed gffReader created " << endl;
    //qDebug() << "Species:  " << speciesName << endl;
    speciesName = "-";
}


void PubMedGffReader::process()
{
    qDebug() << "PubMed gffReader reading file " << gffFileName << endl;

    QFile gff(gffFileName);

    if( !gff.exists() )
    {
        qDebug() << "file not found." << endl;
        return;
    }

    if( ! gff.open(QIODevice::ReadOnly) )
    {
        qDebug() << "file " << gffFileName << " can't be opened." << endl;
        return;
    }
    qDebug() << "file " << gffFileName << " opened." << endl;

    QTextStream inStream(&gff);
    QString line;
    do {
        line = inStream.readLine();

        if( line.contains("#species:") )
        {
            speciesName = line;
            speciesName.remove("#species: ").remove("\n");
            qDebug() << "species name = " << speciesName << endl;
        }

        if( ! line.startsWith("#") && line.size() > 8 )
        {
            //divide line into major tokens- by the tab delim
           QStringList majorTokens = line.split("\t", QString::SkipEmptyParts);

           if( majorTokens.size() <= 8 )
           {
               qDebug() << "Processing gff file failed on file: " << gffFileName << endl;
               qDebug() << "     on line: " << line << endl;
               exit(-1);
           }

           QString seqId;
           QString source;
           QString type;
           int start;
           int stop;
           bool posStrand;
           processFirstColumnsInLine( majorTokens, seqId, source, type, start, stop, posStrand);

           //let's flesh out the rest:
           QString parentContigId = "-";
           bool hasCluster = false;
           QString clusterId = "-";
           bool hasSpecies = false;
           QString species = speciesName; //"-";
           QString id = "-";
           QString name = "-";
           QString product = "-";
           QString parentElement = "-";
           processRemainingData( majorTokens, parentContigId, hasCluster, clusterId,
                                     hasSpecies, species,
                                     id, name, product, parentElement );

           PubMedGenomeElementDataPacket* p = new PubMedGenomeElementDataPacket( seqId, source, type, start, stop, posStrand,
                                                                                 parentContigId, hasCluster, clusterId,
                                                                                 hasSpecies, species,
                                                                                 id, name, product, parentElement );

           emit( dataPacketGenerated( p ) );
        }

     } while (!inStream.atEnd() );

    qDebug() << "done reading gff file " << gffFileName << endl;

    gff.close();

    emit( finished() );
}

//INCOMPLETE!!!
void PubMedGffReader::processRemainingData( QStringList &majorTokens, QString& parentContigId, bool& hasCluster, QString& clusterId,
                                            bool& hasSpecies, QString& species, QString& id, QString& name, QString& product, QString& parentElement )
{
    //-------------------GET CLUSTER INFO-----------------
    if( majorTokens[2].contains("CDS")) //if CDS- will have cluster.  Need to get cluster key.  Cluster id supplied from cdhit algorithm
    {
        hasCluster = true; //RIGHT NOW:  only CDS's will have clusters,
        QString clusterKey;
        if( majorTokens[8].contains("protein_id=") )//This is the code to get the id- id is the cluster id
        {
            QRegExp rx("protein_id=[^;]*;");//ID=any num characters execpt ; then ;
            int pos = rx.indexIn( majorTokens[8]);
            QStringList list = rx.capturedTexts();
            for(int i = 0; i < list.size(); i++)
            {
                clusterKey = list[i].remove("protein_id=").remove(";");//only difference between clusterKey and id is removing .cdna
            }

            //use cluster id to find the cluster
            if( clusterHashTable.contains(clusterKey) )
            {
                clusterId = clusterHashTable.value(clusterKey);
            }
        }
        //qDebug() << "cluster id = " << clusterId << " cluster key = " << clusterKey;
    }

    parentContigId = majorTokens[0];

    if( majorTokens[8].contains("product=") )//This is the code to get the id- id is the cluster id
    {
        QRegExp rx("product=[^;]*;");//ID=any num characters execpt ; then ;
        int pos = rx.indexIn( majorTokens[8]);
        QStringList list = rx.capturedTexts();
        for(int i = 0; i < list.size(); i++)//should be only one
        {
            QByteArray temp;
            temp.append( list[i].remove("product=").remove(";") );
            product = QUrl::fromPercentEncoding( temp );//only difference between clusterKey and id is removing .cdna
        }
    }
    if( majorTokens[8].contains("Name=") )
    {
        QRegExp rx("Name=[^;]*;");//ID=any num characters execpt ; then ;
        int pos = rx.indexIn( majorTokens[8]);
        QStringList list = rx.capturedTexts();
        for(int i = 0; i < list.size(); i++)//should be only one
        {
            name = list[i].remove("Name=").remove(";");//only difference between clusterKey and id is removing .cdna
        }
    }
    if( majorTokens[8].contains("ID=") )
    {
        QRegExp rx("ID=[^;]*;");//ID=any num characters execpt ; then ;
        int pos = rx.indexIn( majorTokens[8]);
        QStringList list = rx.capturedTexts();
        for(int i = 0; i < list.size(); i++)//should be only one
        {
            id = list[i].remove("ID=").remove(";");//only difference between clusterKey and id is removing .cdna
        }
    }


}



